using System;
using System.Linq;
using Microsoft.EntityFrameworkCore;
using MVCDemosoft.Models;
using MVCDmosoft.Db;

namespace MVCDemosoft.Repository
{
    public class EfRepository<T> : IRepository<T> where T : BaseEntity
    {
        private readonly MVCDemosoftDb _Db;
        private readonly DbSet<T> _table;
        public EfRepository()
        {

            _Db = new MVCDemosoftDb();
            _table = _Db.Set<T>();
        }
        public IQueryable<T> Table{
            get{
                return _table.AsQueryable();
            }
        }

        public void Deleted(int id)
        {
            var entity = _table.Where( x => x.Id == id).FirstOrDefault();
            entity.UpdateTime = DateTime.Now;
            entity.isDeleted = true;
            _table.Update(entity);
            _Db.SaveChanges();
        }

        public T GetById(int id)
        {
            var entity = _table.Where( x => x.Id == id && x.isDeleted ==false).FirstOrDefault();
            return entity;
        }

        public void Insert(T entity)
        {
            entity.CreateTime = DateTime.Now;
            entity.UpdateTime = DateTime.Now;
            entity.isActive = false;
            entity.isActive = true;
            _table.Add(entity);
            _Db.SaveChanges();
        }

        public void Update(T entity)
        {
            if( entity == null && entity.Id == 0){
                throw new System.Exception();
            }
            entity.UpdateTime = DateTime.Now;
            _table.Update(entity);
            _Db.SaveChanges();
        }
    }
}